package com.ecommerce.repository;

import com.ecommerce.entity.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
    
    // 根据用户ID查找订单，按创建时间降序
    Page<Order> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);
    
    // 根据用户ID和订单状态查找
    Page<Order> findByUserIdAndStatusOrderByCreatedAtDesc(Long userId, Order.OrderStatus status, Pageable pageable);
    
    // 根据订单号查找
    Optional<Order> findByOrderNumber(String orderNumber);
    
    // 根据用户ID查找订单数量
    Long countByUserId(Long userId);
    
    // 根据用户ID和状态查找订单数量
    Long countByUserIdAndStatus(Long userId, Order.OrderStatus status);
    
    // 查找待付款订单
    @Query("SELECT o FROM Order o WHERE o.userId = :userId AND o.status = 'PENDING' ORDER BY o.createdAt DESC")
    List<Order> findPendingOrders(@Param("userId") Long userId);
}